""" 
    Bookshelf - twExtJS sample use with Pylons
    
    Distributed under the terms of Lesser GNU Public License
    (c) 2007 - Ricardo Girardi Sixel 
"""
import logging
import pylons
from simplejson import JSONDecoder

from bookshelf.lib.base import *
from bookshelf.forms.form import *
from bookshelf.model import *

from toscawidgets.api import WidgetBunch
from toscawidgets.mods.pylonshf import validate, render_response

from toscawidgets.widgets.extJS.data import JSONReader,Record,Store, SortInfo
from toscawidgets.widgets.extJS.grid import EditorGridPanel,ColumnModel, GridColumn
from toscawidgets.widgets.extJS.form import TextField

log = logging.getLogger(__name__)

class BooksController(BaseController):
    def __before__(self):
        c.w = WidgetBunch() 
        
    def index(self):
        #print(dir(model.book))
        books_q = Session.query(Book)
        c.books = books_q.all()
        #c.books_paginator, c.books_set = paginate(model.book,page=1)
        #c.grid_books = GridPanel(fields = colunas_books)
        
        ds = Store(
           url = '/books/list',
           reader = JSONReader(
                        root='result',
                        totalProperty='totalCount',
                        record = Record(data=[{"name":'id'},
                                              {"name":'title'},
                                              {"name":'authors'},
                                              {"name":'publisher'},
                                              {"name":'isbn'},
                                              {"name":'edition'}])
                         ),
           sortInfo = SortInfo(field="title")
          
        )

        columns =[
                GridColumn(
                    name='id',
                    dataIndex="id",
                    header = "Id",
                    width = 50,
                    editor = TextField(name="id",embedded=True),
                    allowBlank = False),
                GridColumn(
                    name='title',
                    isId=True,                    
                    dataIndex = "title",
                    header = "Title",
                    width = 200,
                    editor = TextField(name="title",embedded=True),
                    allowBlank = False),
                GridColumn(
                    name='authors',
                    dataIndex = "authors",
                    header = u"Authors",
                    width = 150,
                    editor = TextField(name="authors",embedded=True),
                    allowBlank = False),
                GridColumn(
                    name='publisher',
                    dataIndex = "publisher",
                    header = u"Publisher",
                    width = 50,
                    editor = TextField(name="publisher",embedded=True),
                    allowBlank = False),                    
                GridColumn(
                    name='isbn',
                    dataIndex = "isbn",
                    header = u"ISBN",
                    width = 80,
                    editor = TextField(name="isbn",embedded=True),
                    allowBlank = False),
                GridColumn(
                    name='edition',
                    dataIndex = "edition",
                    header = u"Edition",
                    width = 60,
                    editor = TextField(name="edition",embedded=True),
                    allowBlank = False)
        ]

        cm = ColumnModel(columns=columns)        

        c.w.booksgrid = EditorGridPanel(
                            ds=ds,
                            cm=cm,
                            renderTo='contentpanel',
                            autoExpandColumn='title',
                            title=u"Books",
                            frame=False,
                            saveUrl='books/savelist'
        )
        
        return render_response('/booklist.html')
    
    @jsonify
    def list(self):
        books_q = Session.query(Book)
        c.books = books_q.all()
        
        books = []
        
        for book in c.books :
            _book = {}
            
            _book['id'] = book.id
            _book['title'] = book.title
            _book['authors'] = book.authors
            _book['publisher'] = book.publisher
            _book['isbn'] = book.isbn
            _book['edition'] = book.edition
                        
            books.append(_book)        
        
        return {'totalCount' : len(c.books) , 'result': books}

    def edit(self,id):
        #print(c.resources)
        books_q = Session.query(Book)
        try:
            book = books_q.filter_by(id=id).one()
        except:
            book = None
        
        if not book:
            book = model.book()
            book.id = 0
            book.data_admissao = datetime.now()
        
        ds = Store(
                   url = '/books/load',
                   reader = JSONReader(
                                 root="result",
                                 totalProperty = "totalCount", 
                                 record = Record(data=[{"name":'id'},
                                                       {"name":'matricula'},
                                                       {"name":'cpf'},
                                                       {"name":'nome'},
                                                       {"name":'senha'}])
                                 ),
                   sortInfo = SortInfo(field="nome")
                  
            )
        
        c.w.form = form.bookToscaForm(ds = ds,height=300)    
        c.value = book        

        return render_response('/bookform.html')
        
    @validate(BookForm(), error_handler="edit")
    def save(self,id):
        if id != 0:        
            books_q = Session.query(Book)
            try:
                book = books_q.filter_by(id=id).one()
            except:
                book = None
        if not book:
            book = model.book()
        book.matricula = request.params['matricula']
        book.cpf = request.params['cpf']
        book.nome = request.params['nome']
        book.senha = request.params['senha']

        Session.save(book)
        Session.commit()   
        
        redirect_to(action = 'success',id=None)

    def delete(self,id):
        books_q = Session.query(Book)
        try:
            book = books_q.filter_by(id=id).one()
        except:
            book = None
        Session.delete(book)
        Session.commit()   
        redirect_to(action='index',id=None)
        
    @jsonify    
    def load(self) :
        books_q = Session.query(Book)
        try:
            book = books_q.filter_by(id=1).one()
        except:
            book = None
            
        _book = {}
        
        _book['id'] = book.id
        _book['matricula'] = book.matricula
        _book['cpf'] = book.cpf
        _book['nome'] = book.nome
        _book['senha'] = book.senha        
        
        return [ _book]
    
    
    @jsonify
    def success(self):
        return [{"success": true, "message": "Saved!"}]  
                
    @jsonify
    def failure(self):
        return [{"success": false, "message": "Problems saving book!"}] 
    
    def savelist(self):
        decoder = JSONDecoder('utf-8')
        for item in request.params.iteritems():
            data = decoder.decode(item[0])
            for i in data:
                books_q = Session.query(Book)
                try:
                    book = books_q.filter_by(id=i['id']).one()
                except:
                    book = Book()    
                book.id = i['id']
                book.title = i['title']
                book.authors = i['authors']
                book.publisher = i['publisher']
                book.isbn = i['isbn']
                book.edition = i['edition']
                
                Session.save(book)
                
        try:
            Session.commit()
            return 'success'
        except:
            return 'failure'
        
               
            
